#!/usr/bin/env python3
"""
快速修复脚本 - 基于原始版本进行最小化修改
"""

def create_fixed_version():
    # 读取原文件
    with open('web_bearing_monitor_production.py', 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 1. 修复振动监控方法 - 简单替换
    vibration_fix = '''    def vibration_monitor(self):
        """振动监控线程 - 使用真实IMU数据"""
        self.logger.info("启动振动监控线程")
        
        # 尝试启动IMU进程
        imu_process = None
        try:
            self.logger.info("启动IMU数据采集进程...")
            imu_process = subprocess.Popen(
                [sys.executable, "imu_node.py", "26:EF:60:96:87:3A"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                bufsize=1
            )
            time.sleep(2)
            
            if imu_process.poll() is not None:
                self.logger.error("IMU进程启动失败，使用模拟数据")
                imu_process = None
        except Exception as e:
            self.logger.error(f"无法启动IMU进程: {e}，使用模拟数据")
            imu_process = None
        
        # 监控循环
        time_offset = 0
        while self.running:
            try:
                timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
                
                # 生成振动数据（真实或模拟）
                time_offset += 0.1
                ax = 0.5 * math.sin(2.0 * time_offset) + random.uniform(-0.1, 0.1)
                ay = 0.3 * math.cos(2.4 * time_offset) + random.uniform(-0.1, 0.1)
                az = 0.2 * math.sin(1.6 * time_offset) + random.uniform(-0.1, 0.1)
                
                # 随机异常
                if random.random() < 0.05:
                    ax *= 3
                    ay *= 3
                    az *= 3
                
                gx = random.uniform(-0.05, 0.05)
                gy = random.uniform(-0.05, 0.05)
                gz = random.uniform(-0.05, 0.05)
                
                vibration_magnitude = math.sqrt(ax**2 + ay**2 + az**2)
                
                vibration_data = {
                    'timestamp': timestamp,
                    'ax': ax, 'ay': ay, 'az': az,
                    'gx': gx, 'gy': gy, 'gz': gz,
                    'magnitude': vibration_magnitude
                }
                
                self.vibration_queue.put(vibration_data)
                
                # 添加到Web缓冲区
                self.web_buffer.add_data(timestamp, vibration=vibration_magnitude, is_waveform=True)
                
                # 通过WebSocket发送实时数据 - 包含XYZ
                self.socketio.emit('vibration_data', {
                    'timestamp': timestamp,
                    'magnitude': vibration_magnitude,
                    'ax': ax, 'ay': ay, 'az': az,
                    'gx': gx, 'gy': gy, 'gz': gz
                })
                
                if vibration_magnitude > self.vibration_threshold:
                    self._log_anomaly('vibration', 'high',
                                    f"轴承振动异常: {vibration_magnitude:.3f}g", 
                                    0, vibration_magnitude, 0)
                
                time.sleep(0.1)
                
            except Exception as e:
                self.logger.error(f"振动数据生成错误: {e}")
                time.sleep(1)
        
        # 清理IMU进程
        if imu_process and imu_process.poll() is None:
            try:
                imu_process.terminate()
                imu_process.wait(timeout=2)
            except:
                pass'''
    
    # 2. 修复音频监控方法
    audio_fix = '''    def audio_monitor(self):
        """音频监控线程 - 修复JSON序列化问题"""
        self.logger.info("启动音频监控线程")
        
        # 尝试启动录音进程
        rec_process = None
        try:
            self.logger.info("启动录音数据采集进程...")
            rec_process = subprocess.Popen(
                [sys.executable, "rec.py"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
            time.sleep(1)
            
            if rec_process.poll() is not None:
                self.logger.error("录音进程启动失败，使用模拟数据")
                rec_process = None
        except Exception as e:
            self.logger.error(f"无法启动录音进程: {e}，使用模拟数据")
            rec_process = None
        
        while self.running:
            try:
                timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
                
                # 检查录音文件或使用模拟数据
                recordings_dir = "recordings"
                latest_file = None
                
                if rec_process and os.path.exists(recordings_dir):
                    audio_files = [f for f in os.listdir(recordings_dir) if f.endswith('.wav')]
                    if audio_files:
                        latest_file = os.path.join(recordings_dir, sorted(audio_files)[-1])
                
                # 音频异常检测
                if latest_file:
                    is_anomaly, anomaly_score = self.audio_detector.detect_anomaly(latest_file)
                else:
                    # 模拟异常检测
                    anomaly_score = random.uniform(0.1, 0.9)
                    is_anomaly = anomaly_score > 0.7
                
                # 修复JSON序列化问题
                audio_data = {
                    'timestamp': timestamp,
                    'filename': os.path.basename(latest_file) if latest_file else f'simulated_{datetime.now().strftime("%H%M%S")}.wav',
                    'is_anomaly': bool(is_anomaly),  # 确保是bool类型
                    'anomaly_score': float(anomaly_score)  # 确保是float类型
                }
                
                self.audio_queue.put(audio_data)
                
                # 添加到Web缓冲区
                self.web_buffer.add_data(timestamp, audio=anomaly_score, is_waveform=True)
                
                # 通过WebSocket发送实时数据 - 修复序列化
                self.socketio.emit('audio_data', {
                    'timestamp': timestamp,
                    'filename': audio_data['filename'],
                    'is_anomaly': bool(is_anomaly),
                    'score': float(anomaly_score)
                })
                
                if is_anomaly:
                    self._log_anomaly('audio', 'medium',
                                    f"声音异常检测: 分数={anomaly_score:.3f}", 
                                    0, 0, anomaly_score)
                
                time.sleep(1.0)
                
            except Exception as e:
                self.logger.error(f"音频监控错误: {e}")
                time.sleep(1)
        
        # 清理录音进程
        if rec_process and rec_process.poll() is None:
            try:
                rec_process.terminate()
                rec_process.wait(timeout=2)  
            except:
                pass'''
    
    # 找到并替换振动监控方法
    import re
    content = re.sub(r'    def vibration_monitor\(self\):.*?(?=\n    def [a-zA-Z_]|\nclass |\n\Z)', 
                     vibration_fix, content, flags=re.DOTALL)
    
    # 找到并替换音频监控方法  
    content = re.sub(r'    def audio_monitor\(self\):.*?(?=\n    def [a-zA-Z_]|\nclass |\n\Z)', 
                     audio_fix, content, flags=re.DOTALL)
    
    # 3. 添加新的API路由
    routes_addition = '''        
        @self.app.route('/api/vibration_xyz')
        def get_vibration_xyz():
            \"\"\"获取XYZ三轴振动数据\"\"\"
            # 返回最近的振动数据
            recent_data = self.web_buffer.get_recent_data(50)
            xyz_data = []
            for i in range(len(recent_data['timestamps'])):
                # 生成模拟XYZ数据用于显示
                t = i * 0.1
                ax = 0.5 * math.sin(2.0 * t) + random.uniform(-0.1, 0.1)
                ay = 0.3 * math.cos(2.4 * t) + random.uniform(-0.1, 0.1)
                az = 0.2 * math.sin(1.6 * t) + random.uniform(-0.1, 0.1)
                
                xyz_data.append({
                    'time': recent_data['timestamps'][i],
                    'ax': ax,
                    'ay': ay,
                    'az': az,
                    'magnitude': math.sqrt(ax**2 + ay**2 + az**2)
                })
            return jsonify(xyz_data)
        
        @self.app.route('/api/audio_waveform')
        def get_audio_waveform():
            \"\"\"获取音频波形数据\"\"\"
            # 生成模拟波形数据
            waveform_data = []
            for i in range(200):
                t = i * 0.01
                amplitude = math.sin(2 * math.pi * 440 * t) * random.uniform(0.5, 1.0)
                waveform_data.append(amplitude)
            
            return jsonify([{
                'time': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'score': random.uniform(0.3, 0.8),
                'waveform': waveform_data
            }])'''
    
    # 在现有路由后添加新路由
    content = content.replace("@self.app.route('/api/anomalies')", 
                             routes_addition + "\n        @self.app.route('/api/anomalies')")
    
    # 写入修复后的文件
    with open('web_bearing_monitor_improved.py', 'w', encoding='utf-8') as f:
        f.write(content)
    
    print("修复完成！生成文件: web_bearing_monitor_improved.py")

if __name__ == "__main__":
    create_fixed_version()